<template>
<!--    供应商报价-->
    <div class="supplier-portal">
        <div class="header">
            <h1>商品标价管理</h1>
            <div class="supplier-info" v-if="currentSupplier.suppliers">
                <span>供货商：{{ currentSupplier.suppliers.name }}</span>
                <span>联系人：{{ currentSupplier.suppliers.contactName}}/{{currentSupplier.suppliers.contactPhone }}</span>
            </div>
        </div>

        <!-- 搜索和筛选工具栏 -->
        <div class="toolbar">
            <div class="search-filter">
                <el-form :inline="true" :model="formInline" class="demo-form-inline">
                    <el-form-item label="名称">
                        <el-input v-model="formInline.searchProductName" placeholder="请输入你要查找的商品名称"></el-input>
                    </el-form-item>
                    <el-form-item label="类别">
                        <template>
                            <el-select v-model="formInline.searchProductType" placeholder="请选择类别">
                                <el-option
                                    v-for="item in productCategory"
                                    :key="item.id"
                                    :label="item.categoryName"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </template>
                    </el-form-item>
                </el-form>


                <el-button
                    type="primary"
                    icon="el-icon-refresh"
                    style="margin-left: 10px;"
                    @click="refreshData"
                >
                    刷新
                </el-button>
            </div>
        </div>

        <!-- 商品表格 -->
        <div class="product-table">
            <el-table
                :data="products"
                stripe
                style="width: 100%"
                v-loading="loading"
                border
            >
                <el-table-column
                    prop="productId"
                    label="商品编码"
                    width="120"
                    sortable
                />

                <el-table-column label="商品图片"
                    width="120" >
                    <template slot-scope="scope">
                        <el-image  :src="scope.row.images[0].imageUrl"></el-image>
                    </template>
                </el-table-column>

                <el-table-column
                    prop="name"
                    label="商品名称"
                    sortable
                />
                <el-table-column
                    prop="productCategory.categoryName"
                    label="分类"
                    width="120">
                    <template slot-scope="scope">
                        {{scope.row.productCategory[0].categoryName}}
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    width="180"
                    fixed="right"
                >
                    <template #default="{row}">
                        <el-button
                            type="info"
                            size="mini"
                            @click="handleEdit(row)"
                            v-if="row.status !== 'approved'"
                        >
                            报价
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="current"
                :page-sizes="pageList"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
            />
        </div>

        <!-- 报价弹框 -->
        <el-dialog
            title="商品报价"
            :visible.sync="priceDialogVisible"
            width="30%"
            :close-on-click-modal="false"
        >
            <el-form :model="quoteForm" label-width="100px">
                <el-form-item label="商品名称">
                    <el-input v-model="quoteForm.productName" disabled></el-input>
                </el-form-item>
                <el-form-item label="新报价" prop="productOffer"
                              :rules="[
            { required: true, message: '请输入报价金额', trigger: 'blur' },
            { type: 'number', message: '必须为数字值', trigger: 'blur' }]"
                >
                    <el-input v-model="quoteForm.productOffer"
                              placeholder="请输入报价金额"
                              @blur="handlePriceBlur">
                        <template slot="append">元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input
                        type="textarea"
                        v-model="quoteForm.remark"
                        placeholder="可填写报价说明或其他备注信息"
                    ></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button @click="priceDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitPrice">确 定</el-button>
      </span>
        </el-dialog>

    </div>
</template>

<script>
export default {
    name: 'ProductPricingManagement',
    data() {
        return {

            currentSupplier: {},//显示供应商信息

            products: [], // 商品列表

            vo: {},
            current: 1,
            pageSize: 10,
            pageList: [10, 15, 20, 30],
            total: 0,

            loading: false,

            // 查询条件
            formInline: {
                searchProductName: '',
                searchProductType: ''
            },

            priceDialogVisible: false, // 控制弹框显示

            quoteForm: {
                productId: '',
                productName: '',
                productOffer: '',
                remark: ''
            },
            currentProduct: null, // 当前操作的商品

            productCategory:[]
        }
    },

    methods: {
        // 查询表格数据
        fetchProductData() {
            this.$axios.post(`product/query/${this.current}/${this.pageSize}`,this.vo).then(r =>{
                this.products = r.data.list;
                this.total = r.data.total;
            })
        },
        //查询供应商信息
        SearchUserSuppliers(){
            let user = JSON.parse(sessionStorage.getItem('user'))
            this.$axios.post(`login/selectIdSuppliers/${user.id}`).then(r =>{
                this.currentSupplier = r.data
            })
        },
        // 查询商品分类
        SearchProductCategory(){
            this.$axios.post(`productCategory/listProductCategory`).then(r =>{
                this.productCategory = r.data
                console.log(444,r.data)
            })
        },

        handleSizeChange(val) {
            this.pageSize = val;
            this.fetchProductData();
        },

        handleCurrentChange(val) {
            this.current = val;
            this.fetchProductData();
        },

        //刷新按钮
        refreshData() {
            this.vo = this.formInline;
            this.fetchProductData();
        },

        // 商品报价 - 打开弹框
        handleEdit(row) {
            this.currentProduct = row;
            this.quoteForm = {
                productId: row.productId,
                productName: row.name,
                productOffer: '',
                remark: ''
            };
            this.priceDialogVisible = true;
            console.log(444,this.quoteForm)

        },
        handlePriceBlur() {
            // 将输入值转为数字（允许小数）
            this.quoteForm.productOffer = parseFloat(this.quoteForm.productOffer) || 0;
        },

        // 提交报价
        submitPrice() {
            // 验证报价是否为有效数字
            if (this.quoteForm.productOffer === null || this.quoteForm.productOffer === '') {
                this.$message.error('请输入报价金额');
                return;
            }

            const offer = parseFloat(this.quoteForm.productOffer);
            if (isNaN(offer)) {
                this.$message.error('报价金额必须为数字');
                return;
            }

            if (offer <= 0) {
                this.$message.error('报价金额必须大于0');
                return;
            }
// 保留2位小数
            const roundedOffer = Math.round(offer * 100) / 100;  // 添加这行

            this.loading = true;
            let user = JSON.parse(sessionStorage.getItem('user'));

            this.$axios.post('quotes/add', {
                productId: this.currentProduct.productId,  // 修改为使用currentProduct
                productOffer: roundedOffer,
                categoryId: this.currentProduct.productCategory[0].id, // 获取正确的分类ID
                userId: user.id,
                remark: this.quoteForm.remark
            }).then(response => {
                this.$message.success('报价提交成功');
                this.priceDialogVisible = false;
                this.fetchProductData();
            }).catch(error => {
                this.$message.error('报价提交失败: ' + (error.message || '未知错误'));
            }).finally(() => {
                this.loading = false;
            });
        }
    },
    created() {
        this.fetchProductData();
        this.SearchUserSuppliers();
        this.SearchProductCategory();
    },
}
</script>

<style scoped>
.supplier-portal {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    font-family: 'Helvetica Neue', Arial, sans-serif;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;

    h1 {
        margin: 0;
        color: #333;
        font-size: 24px;
        font-weight: 500;
    }
}

.supplier-info {
    display: flex;
    gap: 20px;
    font-size: 14px;
    color: #666;

    span {
        display: flex;
        align-items: center;

        &::before {
            content: "";
            display: inline-block;
            width: 4px;
            height: 4px;
            margin-right: 6px;
            background-color: #999;
            border-radius: 50%;
            vertical-align: middle;
        }
    }
}

.toolbar {
    margin-bottom: 20px;

    .search-filter {
        display: flex;
        align-items: center;

        .el-input {
            width: 300px;
        }
    }
}

.product-table {
    margin-bottom: 20px;

    .el-table {
        font-size: 14px;

        ::v-deep .el-table__header th {
            background-color: #f5f7fa;
            font-weight: 600;
        }
    }
}

.pagination {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

@media (max-width: 768px) {
    .header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }

    .supplier-info {
        flex-direction: column;
        gap: 8px;
    }

    .toolbar .search-filter {
        flex-direction: column;
        gap: 10px;

        .el-input {
            width: 100%;
        }

        .el-select, .el-button {
            width: 100%;
            margin-left: 0 !important;
        }
    }

    .pagination {
        justify-content: center;
    }
}
</style>